package controllers

import (
	"db_log_sys/models"
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type DbLogController struct {
	beego.Controller
}

func (c *DbLogController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	order := c.GetString("order")
	page, _ := c.GetInt("page", 1)
	name := c.GetString("name")
	var total int
	var data []models.DbLogTable
	key := fmt.Sprintf("order=%s,page=%d,name=%s", order, page, name)
	JsonGet, _ := models.RDB.Get(models.Ctx, key).Result()
	if JsonGet == "" {
		if err := models.DB.Order(order).Limit(10).Where("db_name like ?", "%"+name+"%").Offset((page - 1) * 10).Find(&data).Error; err != nil {
			c.Data["json"] = map[string]any{
				"Code": 501,
				"Msg":  "服务器繁忙",
			}
			c.ServeJSON()
			return
		}
		JsonSet, _ := json.Marshal(&data)
		models.RDB.Set(models.Ctx, key, JsonSet, 24*time.Hour)
	} else {
		json.Unmarshal([]byte(JsonGet), &data)
	}
	if err := models.DB.Model(&models.DbLogTable{}).Pluck("count(*)", &total).Error; err != nil {
		c.Data["json"] = map[string]any{
			"Code": 502,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]any{
		"Code":  200,
		"Msg":   "查询成功",
		"Data":  data,
		"Total": total,
	}
	c.ServeJSON()
}
func (c *DbLogController) Get() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}

	id, _ := c.GetInt("id")
	var DBLog models.DbLogTable
	key := fmt.Sprintf("id=%d", id)
	JsonGet, _ := models.RDB.Get(models.Ctx, key).Result()
	if JsonGet == "" {
		if err := models.DB.Where("id = ?", id).Limit(1).Find(&DBLog).Error; err != nil {
			c.Data["json"] = map[string]any{
				"Code": 501,
				"Msg":  "服务器繁忙",
			}
			c.ServeJSON()
			return
		}
		JsonSet, _ := json.Marshal(&DBLog)
		models.RDB.Set(models.Ctx, key, JsonSet, 24*time.Hour)
	} else {
		json.Unmarshal([]byte(JsonGet), &DBLog)
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "查询成功",
		"Data": DBLog,
	}
	c.ServeJSON()
}
